<template>
  <div class="upload">
    <!--  :limit="limit" -->
    <el-upload :action="action" :headers="headers" :disabled="disabled" :file-list="fileList" list-type="picture-card"
      :on-preview="handlePictureCardPreview" :before-upload="handleBefore" :on-remove="handleRemove" :limit="limit"
      :on-error="handleSuccess" :on-success="handleSuccess">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-image-viewer  v-if="dialogVisible" :on-close="closeViewer" :initial-index="imageIndex" :url-list="urlList" />
    <!-- <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog> -->
  </div>
</template>

<script>
import { BASEURL } from '../../../public/static/config'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  components: { ElImageViewer },
  props: {
    defaultImage: {
      default: []
    },
    disabled: {
      default: false,
      type: Boolean
    },
		limit: {
		  default: 5,
		  type: Number
		},
    size: {
      default: 0,
      type: Number
    },
    validWidth: {
      default: 0,
      type: Number
    },
    validHeight: {
      default: 0,
      type: Number
    }
  },
  data() {
    return {
      action: (process.env.BASE_URL || BASEURL) + '/common/oss/single',
      fileList: [],
      // limit: 5,
      dialogImageUrl: '',
      dialogVisible: false,
      headers: {
        token: this.$store.state.token
      },
      urlList:[],
      imageIndex: 0
    }
  },
  watch: {
    defaultImage: {
      immediate: true,
      handler(val) {
        this.fileList = val || []
      }
    },
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      
      for (let index = 0; index < this.urlList.length; index++) {
        const url = this.urlList[index];
        if (file.url == url) {
          this.imageIndex = index
          break
        }
      }
      this.dialogVisible = true;
    },
    handleBefore(file, files) {
      if (this.size > 0) {
        const fileSize = file.size / 1024 / 1024 < this.size
        if (!fileSize) {
          this.$message.error('文件大小不能超过' + this.size + 'MB')
          return false
        }
      }
      if (['image/jpeg', 'image/gif', 'image/png', 'image/bmp'].indexOf(
        file.type
      ) === -1
      ) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式')
        return false
      }
      // 如果要验证宽高
      // this.validWidth  由上级组件传入 props 接收
      // this.validHeight 由上级组件传入 props 接收
      if (this.validWidth && this.validHeight) {
        // console.log(this.valWidthAndHeight(file));
        var _this = this
        return new Promise(function (resolve, reject) {
          var reader = new FileReader()
          reader.onload = function (event) {
            var image = new Image()
            image.onload = function () {
              var width = this.width
              var height = this.height
							console.log(width,height);
							console.log(_this.validWidth,_this.validHeight);
              if (width != _this.validWidth && height != _this.validHeight) {
                _this.$alert(
                  '图片宽高必须等于' +
                  _this.validWidth +
                  'px*' +
                  _this.validHeight +
                  'px！',
                  '提示',
                  {
                    confirmButtonText: '确定'
                  }
                )
                reject()
              }
              resolve()
            }
            image.src = event.target.result
          }
          reader.readAsDataURL(file)
        })
      }
    },
    handleSuccess(res, file, fileList) {
      this.loading = false
      this.handleUrlList(fileList)
      if (res && res.code === 200) {
        this.handleMode(res.result, file)
      } else {
        this.$message.error(res.message)
      }
      // this.mode_1.imageUrl = URL.createObjectURL(file.raw);
    },
    handleRemove(file, files) {
      console.log(file, files)
      this.handleUrlList(files)
      this.$emit('update:defaultImage', files)
    },
    handleMode(res, file) {
      this.fileList.push({
        name: file.name,
        url: res,
        uid: file.uid
      })
      this.$emit('update:defaultImage', this.fileList)
    },
    closeViewer() {
      this.dialogVisible = false
    },
    handleUrlList(fileList) {
      if (fileList.length > 0) {
        let urlList = fileList.map(item => {
          return item.response ? item.response.result : item.url
        })
        this.$set(this, 'urlList', urlList)
      }
    }
  }
}
</script>

